package com.example.security_demo.utils;

import javax.servlet.ReadListener;
import javax.servlet.ServletInputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletRequestWrapper;
import java.io.BufferedReader;
import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.nio.charset.Charset;

/**
 *
 *
 * @author zzh
 * @date 2022/5/8
 * @since 1.0
 */
public class RequestWrapper extends HttpServletRequestWrapper {

    /**
     * 通过字节数组来存放  requestBody 中内容
     */
    private final byte[] body;

    public RequestWrapper(HttpServletRequest request) {
        super(request);
        body = RequestParseUtil.getBodyString(request).getBytes(Charset.defaultCharset());
    }

    @Override
    public BufferedReader getReader() throws IOException {
        return new BufferedReader(new InputStreamReader(getInputStream()));
    }

    @Override
    public ServletInputStream getInputStream() {

        ByteArrayInputStream in = new ByteArrayInputStream(body);

        return new ServletInputStream() {
            @Override
            public boolean isFinished() {
                return false;
            }

            @Override
            public boolean isReady() {
                return false;
            }

            @Override
            public void setReadListener(ReadListener readListener) {

            }

            @Override
            public int read() {
                return in.read();
            }
        };
    }
}
